package com.itcast.activiti.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.activiti.domain.Menu;
import com.itcast.activiti.entity.ActIdPassUser;
import com.itcast.activiti.entity.ActIdProcess;
import com.itcast.activiti.mapper.ActIdProcessMapper;
import com.itcast.activiti.service.IActIdPassUserService;
import com.itcast.activiti.service.IActIdProcessService;
import com.itcast.activiti.utils.MenuTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 自定义流程类别 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2021-03-03
 */
@Service
public class ActIdProcessServiceImpl extends ServiceImpl<ActIdProcessMapper, ActIdProcess> implements IActIdProcessService {
    @Autowired
    private IActIdPassUserService iActIdPassUserService;

    @Override
    public List<Menu> listActIdProcess(Integer actIdProcessId) {
//        List<Integer> permissionIds = iActIdPassUserService.listActIdPassUserByActIdProcess(actIdProcessId)
//                .stream()
//                .map(ActIdPassUser::getActIdProcessId)
//                .collect(Collectors.toList());
        List<ActIdProcess> permissions = baseMapper.selectList(new QueryWrapper<ActIdProcess>().lambda().eq(ActIdProcess::getDeleted, false).orderByAsc(ActIdProcess::getSort));
        List<Menu> menuList = new ArrayList<>();
        List<Menu> finalMenuList = menuList;
        permissions.forEach(permission -> {
            finalMenuList.add(new Menu(permission.getId(), permission.getParentId(), permission.getName(), permission.getType()));
        });
        MenuTree menuTree = new MenuTree(finalMenuList, null);
        menuList = menuTree.builTree();
        return menuList;
    }

    @Override
    public ActIdProcess getActIdProcess(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public boolean addActIdProcess(ActIdProcess actIdProcess) {
        return baseMapper.insert(actIdProcess) == 1;
    }

    @Override
    public boolean editActIdProcess(ActIdProcess actIdProcess) {
        Assert.notNull(actIdProcess.getId(), "id is empty");
        return baseMapper.updateById(actIdProcess) == 1;
    }

    @Override
    public boolean delActIdProcess(Integer id, String deletedBy) {
        ActIdProcess actIdProcess = new ActIdProcess();
        actIdProcess.setId(id);
        actIdProcess.setDeletedBy(deletedBy);
        actIdProcess.setDeletedDatetime(LocalDateTime.now());
        actIdProcess.setDeleted(true);
        return baseMapper.updateById(actIdProcess) == 1;
    }
}
